package com.atguigu.gulimall.auto.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auto.feign.MemberFeignService;
import com.atguigu.gulimall.auto.vo.UserLoginVo;
import com.atguigu.gulimall.auto.vo.UserRegisterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author kabuda
 * @create 2022-11-28 22:18
 */
@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam(value = "phone",required = false) String phone){

        String code_time = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + phone);
        if(!StringUtils.isEmpty(code_time)){
            Long time= Long.valueOf(code_time.split("_")[1]);
            //如果发送间隔小于60s，无效
            if(System.currentTimeMillis()-time<60000){
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
        //存验证码，有效期是十分钟
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_PREFIX+phone,code,10, TimeUnit.MINUTES);
        //模拟验证码，控制台输出
        System.out.println(phone+":"+code);
        return R.ok();
    }


    @PostMapping("/register")
    public String register(@Valid UserRegisterVo registerVo, BindingResult result, RedirectAttributes attributes){
        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(filedError -> filedError.getField(), filedError -> filedError.getDefaultMessage(),(item1,item2)->item1));
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //判断验证码
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + registerVo.getPhone());
        if(!StringUtils.isEmpty(s)){
           String codeRedis= s.split("_")[0];
            if(codeRedis.equals(registerVo.getCode())){
                //验证码正确，删除redis验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_PREFIX + registerVo.getPhone());
                //注册会员
                R r = memberFeignService.register(registerVo);
                if(r.getCode()==0){
                    return "/login.html";
                }else{
                    Map<String, String> errors = new HashMap<>();
                    String msg = r.getData("msg",new TypeReference<String>() {
                    });
                    errors.put("msg",msg);
                    attributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else{
                // 验证码错误
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            //redis存储验证码失效
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码失效，请重新发送");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes, HttpSession session){
        //登录判断
        R r = memberFeignService.login(vo);
        if(r.getCode()==0){
            MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }
        //账号或密码错误
        Map<String, String> errors = new HashMap<>();
        errors.put("msg","账号或密码错误");
        attributes.addFlashAttribute("errors",errors);
        return "redirect:http://auth.gulimall.com/login.html";

    }



}
